#!/usr/bin/perl
use Test::More;

BEGIN {
    $basedir = $0;
    $basedir =~ s|(.*)/[^/]*|$1|;

    # allow info to be shown during tests
    $v = $ARGV[0];
    if ($v) {
        if ( $v ne "-v" ) {
            plan skip_all => "Invalid option (use -v)";
        }
    }
    else {
        $v = " ";
    }

    plan tests => 14;
}

############ Test tun_socket TUN #############
print "Test TUN device driver support - 'tun_socket'\n";
$result = system "runcon -t test_tun_tap_t $basedir/tun_tap $v -s";
ok( $result eq 0 );

# Deny capability { net_admin } - EPERM
$result =
  system "runcon -t test_tun_tap_no_net_admin_t $basedir/tun_tap $v 2>&1";
ok( $result >> 8 eq 1 );

# Deny tun_socket { create } - EACCES
$result = system "runcon -t test_tun_tap_no_create_t $basedir/tun_tap $v 2>&1";
ok( $result >> 8 eq 13 );

# Deny tun_socket { attach_queue } - EACCES
$result = system "runcon -t test_tun_tap_no_queue_t $basedir/tun_tap $v 2>&1";
ok( $result >> 8 eq 13 );

$result = system
  "runcon -t test_tun_tap_t $basedir/tun_relabel $v test_newcon_tun_tap_t";
ok( $result eq 0 );

# Deny tun_socket { relabelto } - EACCES
$result = system
"runcon -t test_tun_tap_t $basedir/tun_relabel $v test_newcon_no_to_tun_tap_t 2>&1";
ok( $result >> 8 eq 13 );

# Deny tun_socket { relabelfrom } - EACCES
$result = system
"runcon -t test_tun_tap_t $basedir/tun_relabel $v test_newcon_no_from_tun_tap_t 2>&1";
ok( $result >> 8 eq 13 );

############ Test tun_socket TAP #############
print "Test TAP device driver support - 'tun_socket'\n";
$result = system "runcon -t test_tun_tap_t $basedir/tun_tap -p $v";
ok( $result eq 0 );

# Deny capability { net_admin } - EPERM
$result =
  system "runcon -t test_tun_tap_no_net_admin_t $basedir/tun_tap -p $v 2>&1";
ok( $result >> 8 eq 1 );

# Deny tun_socket { create } - EACCES
$result =
  system "runcon -t test_tun_tap_no_create_t $basedir/tun_tap -p $v 2>&1";
ok( $result >> 8 eq 13 );

# Deny tun_socket { attach_queue } - EACCES
$result =
  system "runcon -t test_tun_tap_no_queue_t $basedir/tun_tap -p $v 2>&1";
ok( $result >> 8 eq 13 );

$result = system
  "runcon -t test_tun_tap_t $basedir/tun_relabel -p $v test_newcon_tun_tap_t";
ok( $result eq 0 );

# Deny tun_socket { relabelto } - EACCES
$result = system
"runcon -t test_tun_tap_t $basedir/tun_relabel -p $v test_newcon_no_to_tun_tap_t 2>&1";
ok( $result >> 8 eq 13 );

# Deny tun_socket { relabelfrom } - EACCES
$result = system
"runcon -t test_tun_tap_t $basedir/tun_relabel -p $v test_newcon_no_from_tun_tap_t 2>&1";
ok( $result >> 8 eq 13 );

exit;
